package com.yp.shopping.service.Impl;

import com.yp.shopping.bean.GetResult;
import com.yp.shopping.bean.Result;
import com.yp.shopping.dao.CategoryMapper;
import com.yp.shopping.dao.GoodsCategoryMapper;
import com.yp.shopping.model.Category;
import com.yp.shopping.model.CategoryExample;
import com.yp.shopping.model.GoodsCategory;
import com.yp.shopping.model.GoodsCategoryExample;
import com.yp.shopping.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;

    public Result saveCategory(Category category) {

        categoryMapper.insert(category);

        return GetResult.success();
    }

    public List<Category> getCategories() {

        CategoryExample categoryE = new CategoryExample();

        categoryE.or().andIdIsNotNull();

        return categoryMapper.selectByExample(categoryE);
    }

    public Category getCategoryById(Integer id) {

        return categoryMapper.selectByPrimaryKey(id);
    }

    public Result deleteCategoryById(Integer id) {

        GoodsCategoryExample goodsCategoryE = new GoodsCategoryExample();

        goodsCategoryE.or().andCategoryIdEqualTo(id).andGoodsIdIsNotNull();

        List<GoodsCategory> goodsCategories = goodsCategoryMapper.selectByExample(goodsCategoryE);

        if (goodsCategories.size() == 0) {

            categoryMapper.deleteByPrimaryKey(id);
        } else {

            return GetResult.fail();
        }

        return GetResult.success();
    }

    public Category updateCategory(Category category) {

        categoryMapper.updateByPrimaryKey(category);

        return category;
    }
}
